package android

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"golang.org/x/text/encoding/simplifiedchinese"
	"io"
	"log"
	"net/http"
	"os/exec"
	"strconv"
	"strings"
	"time"
)

var ApiKey string

func SliceIndex[T int | string](arr []T, e T) int {
	for i, a := range arr {
		if a == e {
			return i
		}
	}
	return -1
}

func ExecPowerCmdChina(call string) (res, e string) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	cmd := exec.CommandContext(ctx, "powershell", "-Command", call)
	var stderr bytes.Buffer
	cmd.Stderr = &stderr
	out, err := cmd.Output()
	if ctx.Err() != nil {
		log.Println(cmd.String(), " timeout")
		e = "timeout"
		return
	}
	decoder := simplifiedchinese.GB18030.NewDecoder()
	if err != nil {
		e, err = decoder.String(stderr.String())
		return
	}
	res, err = decoder.String(string(out))
	if err != nil {
		log.Println(err.Error())
		return "", err.Error()
	}
	return
}

func sToi(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		return 0
	}
	return i
}

func Bs64(s string) string {
	return base64.StdEncoding.EncodeToString([]byte(s))
}

func HandleMsgRobot(msg string) string {
	if msg == "" {
		msg = "讲个笑话"
	}
	resp, err := http.Get("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + msg)
	if err != nil {
		Log.Println("get resp failed: " + err.Error())
		return "get resp failed: " + err.Error()
	}
	defer resp.Body.Close()
	data, err := io.ReadAll(resp.Body)
	if err != nil {
		Log.Println("get resp failed: " + err.Error())
		return "get resp failed: " + err.Error()
	}
	var m map[string]interface{}
	err = json.Unmarshal(data, &m)
	if err != nil {
		Log.Println("get resp failed: " + err.Error())
		return "get resp failed: " + err.Error()
	}
	if m["result"].(float64) == 0 {
		return strings.ReplaceAll(m["content"].(string), "{br}", "\n")
	}
	Log.Println("get resp failed")
	return "get resp failed"
}

func HandleMsgGPT(msg string) string {
	if msg == "" {
		msg = "讲个冷笑话"
	}
	var data = `{"isBrowser":false,"openaiKey":"` + ApiKey + `","prompt":"` + msg + `","options":{"conversationId":"729111688315326993",
	"systemMessage":"我想让你充当一个高中男生，但是你的回答带有小孩子味儿，你喜欢称呼对方为姐姐，你喜欢说些发脾气的语气词，注意回答最好不要超过20字除非有必要","completionParams":{"presence_penalty":0.8,"temperature":1,"model":"gpt-3.5-turbo-16k-0613"}}}`
	for {
		resp, err := http.Post("https://ai.usesless.com/api/chat-process", "application/json", bytes.NewBuffer([]byte(data)))
		if err != nil {
			Log.Println("get resp failed: " + err.Error())
			return "get resp failed: " + err.Error()
		}
		res, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			Log.Println("get resp failed: " + err.Error())
			return "get resp failed: " + err.Error()
		}
		if strings.Contains(string(res), "key有误") {
			Log.Println("get resp failed: " + "key有误")
			return "key有误"
		}
		arr := strings.Split(string(res), "\n")
		if len(arr) >= 2 {
			data = arr[len(arr)-2]
			var m map[string]interface{}
			err = json.Unmarshal([]byte(data), &m)
			if err != nil {
				Log.Println("get resp failed: " + err.Error())
				return "get resp failed: " + err.Error()
			}
			if m["text"] == nil {
				Log.Println("get resp failed: " + err.Error())
				return "get resp failed: " + err.Error()
			}
			return m["text"].(string)
		} else {
			time.Sleep(time.Second)
		}
	}
}

func CheckApiKey() bool {
	return "key有误" != HandleMsgGPT("你好")
}
